package com.example.oop.ServerOperation.Server;

import com.example.oop.ServerOperation.NetOperation.NetConnection;
import com.example.oop.Service.ServiceHandler;
import com.example.oop.Threads.FindReadyPlayer;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    private ServerSocket serverSocket;

    public void initialServer() {
        try {
            serverSocket = new ServerSocket(2022);
        } catch (IOException e) {
            System.out.println("ServerSocket创建失败，可能是接口被占用！");
            e.printStackTrace();
        }
        System.out.println("服务器启动成功！");

        //启动匹配线程
        FindReadyPlayer.findReadyPlayer.start();

        while (true) {
            // 监听请求,阻塞等待,直到有客户端发起连接
            Socket socket = null;  //阻塞当前代码，直到收到前端请求
            try {
                socket = serverSocket.accept();
            } catch (IOException e) {
                System.out.println("socket接受请求错误！");
                e.printStackTrace();
            }
            //创建连接
            NetConnection connection = new NetConnection(socket);
            // 创建一个线程，在线程里处理这个请求
            //对连接的操作由该该子线程全权负责
            ServiceHandler handler = new ServiceHandler(connection);
            //启动线程
            handler.start();
        }
    }
}





